<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON</title>
    <script>
        function f1(){
            let user = {"id":1,"username":"admin","password":"123456"};
            console.log(user.id);
            console.log(user.username);
            console.log(user['password']);
        }
        function f2(){
            let dept = {"id":1,"name":"研发部","remark":"负责研发产品的"};
            let emp = {"id":1,"name":"admin","salary":8000,"dept":dept};
            console.log(emp.id);
            console.log(emp.name);
            console.log(emp.salary);
            console.log(emp.dept.id);
            console.log(emp.dept['name']);
            console.log(emp.dept["remark"]);
        }
        function f3(){
            let users = [{
                "id":1,
                "username":"admin",
                "password":"123456"
            },{
                "id":2,
                "username":"alice",
                "password":"111111"
            },{
                "id":3,
                "username":"jack",
                "password":"222222"
            }];
            console.log(users[0].id)
            console.log(users[1].id)
            console.log(users[2].id)
        }
        function f4(){
            let userString = "{'id':1,'username':'admin','password':'123456'}";
            console.log(typeof userString)
            // 在将一个JSON格式的字符串转换成JSON对象时,有两种方式
            // 1.eval()
            // 该方式属于通用型,对于转换前的字符串没有严格要求,只要符合JSON格式即可
            // 安全性较低
            let user = eval("("+userString+")");
            // 2.JSON.parse()
            // 该方式对转换前的字符串存在严格要求,要求此时的JSON格式的字符串必须通过单引号表示
            // 安全性较高
            // let user = JSON.parse(userString); // 无效
            console.log(typeof  user);
            console.log(user.id);
            console.log(user.username);
            console.log(user.password);
        }
        function f5(){
            let userString = '{"id":1,"username":"admin","password":"123456"}';
            console.log(typeof userString)
            // let user = eval("("+userString+")");
            let user = JSON.parse(userString);
            console.log(typeof  user);
            console.log(user.id);
            console.log(user.username);
            console.log(user.password);


        }
    </script>
</head>
<body>
<button onclick="f1()">基本用法</button><br>
<button onclick="f2()">对象中包含对象</button><br>
<button onclick="f3()">对象数组</button><br>
<button onclick="f4()">JSON格式字符串</button><br>
<button onclick="f5()">JSON格式字符串</button><br>
</body>
</html>